package booksystem.controller;

import booksystem.utils.VerifyCodeUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

@WebServlet("/imgCode")
public class ImageCodeServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        //设置响应格式
        response.setContentType("image/jpeg");
        //获得验证码的map
        Map<String, BufferedImage> map = VerifyCodeUtils.getMap();
        //获取map中的图片
        BufferedImage img = VerifyCodeUtils.getImage(map);
        //获取map中的数据
        String code = VerifyCodeUtils.getCode(map);
        // 将验证码保存到session中
        HttpSession session = request.getSession();
        session.setAttribute("code", code);
        //将图片放入输出流中，写到网页上
        ImageIO.write(img,"jpeg",response.getOutputStream());
    }
}
